<template>
  <div class="statistics-filter" v-if="formAnalysis" style="width: 100%">
    <el-table :data="formAnalysis.list.formAnalysisData" style="width: 100%" stripe border>
      <el-table-column prop="status" label="状态" align="center" fixed="right">
        <template #default="{ row }">
          {{ row.status == 0 ? '待审核' : (row.status == 1 ? '已通过' : '未通过') }}
        </template>
      </el-table-column>
      <el-table-column prop="index" label="操作" align="center" fixed="right">
        <template #default="{ row }">
          <div class="btns">
            <el-button type="primary" link @click="goAnswerDetail(row)">详情</el-button>
            <el-dropdown>
              <i class="iconfont more-icon">&#xe6dc;</i>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="row.status == 0 || row.status == 2">
                    <span @click="handleAnswerAudit(row, 1)"><i class="iconfont">&#xe693;</i>标记为通过</span>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="row.status == 0 || row.status == 1">
                    <span @click="handleAnswerAudit(row, 2)"><i class="iconfont">&#xe695;</i>标记为未通过</span>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <span @click="deleteAnswer(row)"><i class="iconfont">&#xe718;</i>删除</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-for="(item, index) in formAnalysis.formAnalysisProp" :key="index" :prop="item.prop"
        :label="item.label" :fixed="item.prop == 'index'" align="center" :render-header="renderHeader"
        show-overflow-tooltip>
        <template #default="{ row }">
          <!-- 附件/图片 -->
          <template v-if="item.prop.includes('fileUpload') || item.prop.includes('imgUpload')">
            <div class="file-box">
              <span class="file" v-for="(file, fileIndex) in row[item.prop]" :key="fileIndex"
                @click="downLoadFile(file)">
                {{ file.fileName }}
              </span>
            </div>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <slot name="footer-pagenation"></slot>
    <el-dialog v-if="answerDetailOpen" v-model="answerDetailOpen" title="答卷详情" align-center width="740px"
      @close="answerDetailClose">
      <div class="preview-form" v-loading="answerDetailLoading">
        <div class="publish-info">
          <div>
            <span class="label">序号：</span>
            <span>{{ curRow.index }}</span>
          </div>
          <div>
            <span class="label">状态：</span>
            <span
              :style="{ 'color': filterAnswerStatus(curRow.status).color }">{{ filterAnswerStatus(curRow.status).label }}</span>
          </div>
          <div>
            <span class="label">提交时间：</span>
            <span>{{ curRow.answerTime }}</span>
          </div>
          <div>
            <el-button v-if="curRow.status == 0 || curRow.status == 2" size="small" @click="handleAnswerAudit(curRow, 1)" type="primary">标记通过</el-button>
            <el-button v-if="curRow.status == 0 || curRow.status == 1" size="small" @click="handleAnswerAudit(curRow, 2)" type="">标记不通过</el-button>
          </div>
        </div>
        <el-scrollbar max-height="70vh" v-if="!answerDetailLoading">
          <FormEcho :formData="answerDetail" :modelValue="answerForm" height="70vh" :disabled="true" :showDevice="false" :simple="true" />
        </el-scrollbar>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="preAnswerDetail" :disabled="curRowIndex <= 0">上一份</el-button>
          <el-button type="" @click="nextAnswerDetail"
            :disabled="curRowIndex >= formAnalysis.list.formAnalysisData.length - 1">
            下一份
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, computed, watch } from 'vue'
import { getAnswerDetail, deleteAnswerByIds, updatePaperResultState } from "@/api/formDesign";
// import { fileSecretKey } from "@/views/form/manage/design/config/formCmpConfig.js";
import { ElMessageBox, ElMessage } from 'element-plus'
import { FormEcho } from '@ruifox-cms/components'
import { useStore } from 'vuex'

const props = defineProps({
  formAnalysis: {
    type: Object,
    default: () => {}
  },
  formReport: {
    type: Object,
    default: () => {}
  }
})
const emits = defineEmits(['refreshData'])
const store = useStore()
const curFormId = computed(() => props.formReport.id)
const curFormType = computed(() => props.formReport.qsType)
const formAnalysis = computed(() => props.formAnalysis)
const answerDetailOpen = ref(false)
const answerDetail = ref()
const answerForm = ref({})
const answerDetailLoading = ref()
const curRow = ref()
const curRowIndex = ref()
// 查看详情
const goAnswerDetail = async (row) => {
  curRow.value = row
  console.log('curRow', curRow.value);
  curRowIndex.value = formAnalysis.value.list.formAnalysisData.findIndex(item => item.id == curRow.value.id)
  answerDetailLoading.value = true
  let res = await getAnswerDetail({ id: row.id, formId: curFormId.value })
  answerDetail.value = res.data
  answerDetail.value.answerTime = row.answerTime
  res.data.formItemList.forEach(item => {
    answerForm.value[item.formItemId] = item.modelValue
  })
  if (curFormType.value == 4) {
    store.commit('formDesignInfo/SET_isExamAudit', true)
  }
  answerDetailLoading.value = false
  answerDetailOpen.value = true
}
watch(answerDetail, (val) => {
  curRow.value.score = val.formItemList.reduce((total, item) => {
    return total + (item.modelScore || 0)
  }, 0)
}, { deep: true })
// 上一份
const preAnswerDetail = () => {
  curRow.value = formAnalysis.value.list.formAnalysisData[curRowIndex.value - 1]
  goAnswerDetail(curRow.value)
}
// 下一份
const nextAnswerDetail = () => {
  curRow.value = formAnalysis.value.list.formAnalysisData[curRowIndex.value + 1]
  goAnswerDetail(curRow.value)
}
const answerStatusOption = ref([
  { label: '待审核', value: 0, color: '#333' },
  { label: '已通过', value: 1, color: 'green' },
  { label: '未通过', value: 2, color: 'red' },
])
const filterAnswerStatus = (status) => {
  return answerStatusOption.value.find(item => item.value == status)
}
// 答卷审核
const handleAnswerAudit = async (row, status) => {
  ElMessageBox.prompt('请输入原因，非必填', '标记为不通过', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async ({value}) => {
    let res = await updatePaperResultState({ id: row.id, state: status, reviewOpinion: value })
    if (res.code == 20000) {
      row.status = status
      ElMessage({
        showClose: true,
        message: '操作成功',
        type: 'success'
      })
    }
  })
}

// 删除
const deleteAnswer = (row) => {
  let ids = []
  if (row) {
    ids = [row.id]
  }
  ElMessageBox.confirm(
    '<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除答卷？</p><span style="font-size: 14px;color: #FF5240;">清除后内容将无法恢复</span></div>',
    '删除确认',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    }
  ).then(async () => {
    let res = await deleteAnswerByIds({ ids, formId: curFormId.value })
    if (res.code == 20000) {
      ElMessage({
        showClose: true,
        message: '删除成功',
        type: 'success'
      })
      emits('refreshData')
    }
  })
}
// 表头部重新渲染
const renderHeader = ({ column }) => {
  const span = document.createElement('span')
  span.innerText = column.label
  document.body.appendChild(span)
  let fixedArr = [
    { prop: 'answerTime', width: 160 },
    { prop: 'resource', width: 130 },
    { prop: 'ip', width: 130 },
  ]
  let minWidth = span.getBoundingClientRect().width + 30
  let fixObj = fixedArr.find(item => item.prop == column.property)
  if (fixObj) minWidth = fixObj.width
  column.minWidth = minWidth < 80 ? 80 : minWidth
  document.body.removeChild(span)
  return column.label
}
// 下载附件
const downLoadFile = (file) => {
  window.open(file.url)
}
// 审核页面关闭
const answerDetailClose = () => {
  store.commit('formDesignInfo/SET_isExamAudit', false)
}
</script>
<style scoped lang='scss'>
.statistics-filter {
  margin-top: 20px;

  .file-box {
    display: flex;
    flex-direction: column;

    .file {
      margin-right: 10px;
      color: $mainColor;
      cursor: pointer;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

.btns {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .more-icon {
    cursor: pointer;
    font-size: 22px;
    margin-left: 10px;
    color: $mainColor;
  }
}

.preview-form {
  min-height: 700px;

  .publish-info {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    &>div:not(:last-child) {
      margin-right: 40px;

      .label {
        color: #999;
      }
    }
  }
}
</style>